package org.luxor.commons.core.utils;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 字符串工具类, 继承org.apache.commons.lang.StringUtils类
 *
 * @author admin
 */
public class StringUtils extends org.apache.commons.lang.StringUtils {

    /**
     * 转换为字节数组
     */
    public static byte[] getBytes(String str) {
        if (str != null) {
            try {
                return str.getBytes(StrKit.CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    /**
     * 转换为字节数组
     */
    public static String toString(byte[] bytes) {
        try {
            return new String(bytes, StrKit.CHARSET_NAME);
        } catch (UnsupportedEncodingException e) {
            return StrKit.EMPTY;
        }
    }

    /**
     * 转换为String
     */
    public static String toString(Object obj) {
        if (obj == null) {
            return StrKit.EMPTY;
        }
        if (obj instanceof String) {
            return obj.toString();
        }
        return obj + StrKit.EMPTY;
    }

    /**
     * 异常转换为String
     */
    public static String toString(Throwable e) {
        if (e == null) {
            return StrKit.EMPTY;
        }
        StringWriter swriter = new StringWriter();
        PrintWriter pwriter = new PrintWriter(swriter);
        e.printStackTrace(pwriter);
        pwriter.flush();
        swriter.flush();
        String str = swriter.toString();
        IOUtils.closeQuietly(pwriter, swriter);
        return str;
    }

    public static boolean isEmpty(String str) {
        return !isNotEmpty(str);
    }

    public static String trimSpace(String source) {
        return source == null ? source : source.replaceAll("^[\\s　]*|[\\s　]*$", StrKit.EMPTY);
    }

    public static String[] copy(String[] source) {
        if (source == null) {
            return null;
        }
        int length = source.length;
        String[] result = new String[length];
        System.arraycopy(source, 0, result, 0, length);
        return result;
    }

    public static String reverse(String s) {
        if (s == null) {
            return null;
        }
        char[] c = s.toCharArray();
        char[] reverse = new char[c.length];
        for (int i = 0; i < c.length; i++) {
            reverse[i] = c[c.length - i - 1];
        }
        return new String(reverse);
    }

    public static boolean startsWith(String s, String start) {
        if ((s == null) || (start == null)) {
            return false;
        }
        if (start.length() > s.length()) {
            return false;
        }
        String temp = s.substring(0, start.length());
        if (temp.equalsIgnoreCase(start)) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean contain(Collection<String> strs, String str) {
        if (str != null) {
            for (String s : strs) {
                if (str.equals(trim(s))) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean contain(String[] strs, String str) {
        if (str != null) {
            for (String s : strs) {
                if (str.equals(trim(s))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 驼峰命名法工具
     *
     * @return toCamelCase(" hello_world ") == "helloWorld"
     * toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = s.toLowerCase();
        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (String.valueOf(c).equals(StrKit.UNDERLINE)) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 驼峰命名法工具
     *
     * @return toCamelCase(" hello_world ") == "helloWorld"
     * toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toCapitalizeCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = toCamelCase(s);
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }

    /**
     * 驼峰命名法工具
     *
     * @return toCamelCase(" hello_world ") == "helloWorld"
     * toCapitalizeCamelCase("hello_world") == "HelloWorld"
     * toUnderScoreCase("helloWorld") = "hello_world"
     */
    public static String toUnderScoreCase(String s) {
        if (s == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            boolean nextUpperCase = true;
            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }
            if ((i > 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    sb.append(StrKit.UNDERLINE);
                }
                upperCase = true;
            } else {
                upperCase = false;
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }


    /**
     * URL编码
     */
    public static String urlEncode(String url) {
        try {
            return URLEncoder.encode(url, "UTF-8" );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * URL解码
     */
    public static String urlDecode(String url) {
        try {
            return URLDecoder.decode(url, "UTF-8" );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * URL后添加参数
     */
    public static String urlAppendParam(String url, String key, String value) {
        int routingIndex = url.indexOf("#" );
        String prefixUrl;
        String suffixUrl = "";
        if (routingIndex > -1) {
            prefixUrl = url.substring(0, routingIndex);
            suffixUrl = url.substring(routingIndex);
        } else {
            prefixUrl = url;
        }
        char connSymbol = '?';
        if (indexOf(prefixUrl, "?" ) > -1) {
            connSymbol = '&';
        }
        return prefixUrl + connSymbol + key + '=' + value + suffixUrl;
    }

    public static String[] merge(String[] _arr1, String[] _arr2) {
        if (_arr1 == null) {
            return _arr2;
        }
        if (_arr2 == null) {
            return _arr1;
        }
        int length1 = _arr1.length;
        int length2 = _arr2.length;
        if (length1 + length2 <= 0) {
            return null;
        }
        String[] newArr = new String[length1 + length2];
        if (length1 > 0) {
            System.arraycopy(_arr1, 0, newArr, 0, length1);
        }
        if (length2 > 0) {
            System.arraycopy(_arr2, 0, newArr, length1, length2);
        }
        return newArr;
    }

    public static List<String> splitAsList(String s, String delimiter) {
        List<String> collections = new ArrayList<>();
        if (s == null || s.length() <= 0) {
            return collections;
        }
        if (delimiter == null || delimiter.length() <= 0) {
            collections.add(s);
            return collections;
        }
        if (!s.endsWith(delimiter)) {
            s += delimiter;
        }
        if (s.equals(delimiter)) {
            return collections;
        }
        if ("\n".equals(delimiter) || "\r".equals(delimiter)) {
            try {
                BufferedReader br = new BufferedReader(new StringReader(s));
                String line;
                while ((line = br.readLine()) != null) {
                    collections.add(line);
                }
                br.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        } else {
            int offset = 0;
            int pos = s.indexOf(delimiter, offset);
            while (pos != -1) {
                collections.add(s.substring(offset, pos));
                offset = pos + delimiter.length();
                pos = s.indexOf(delimiter, offset);
            }
        }
        return collections;
    }

    public static String replace(String s, String oldSub, String newSub) {
        if ((s == null) || (oldSub == null) || (newSub == null)) {
            return null;
        }
        int y = s.indexOf(oldSub);
        if (y >= 0) {
            StringBuffer sb = new StringBuffer();
            int length = oldSub.length();
            int x = 0;
            while (x <= y) {
                sb.append(s.substring(x, y));
                sb.append(newSub);
                x = y + length;
                y = s.indexOf(oldSub, x);
            }
            sb.append(s.substring(x));
            return sb.toString();
        } else {
            return s;
        }
    }

    public static String replace(String s, String[] oldSubs, String[] newSubs) {
        if ((s == null) || (oldSubs == null) || (newSubs == null)) {
            return null;
        }
        if (oldSubs.length != newSubs.length) {
            return s;
        }
        for (int i = 0; i < oldSubs.length; i++) {
            s = replace(s, oldSubs[i], newSubs[i]);
        }
        return s;
    }

    public static boolean notEquals(String str1, String str2) {
        return !equals(str1, str2);
    }

    public static boolean notEqualsIgnoreCase(String str1, String str2) {
        return !equalsIgnoreCase(str1, str2);
    }
}
